import toTop from '@/assets/svg/toTop.svg';
import { useEffect, useState } from 'react';
import styles from './index.less';

export default ({ targetRef }) => {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const toggleVisibility = () => {
      const element = targetRef?.current || document.documentElement;
      const scrollTop = element.scrollTop;
      if (scrollTop > 300) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    if (targetRef?.current) {
      const element = targetRef.current;
      element.addEventListener('scroll', toggleVisibility);
      return () => {
        element.removeEventListener('scroll', toggleVisibility);
      };
    } else {
      window.addEventListener('scroll', toggleVisibility);
      return () => {
        window.removeEventListener('scroll', toggleVisibility);
      };
    }
  }, []);

  const scrollToTop = () => {
    const element = targetRef?.current || document.documentElement;
    element.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };
  return (
    <img
      onClick={scrollToTop}
      style={{ display: !isVisible && 'none' }}
      className={styles.toTopBtn}
      src={toTop}
    />
  );
};
